package com.toycloud.business.controller.upload;

import com.iflytek.cssp.CSSPClient;
import com.iflytek.cssp.exception.CSSPException;
import com.iflytek.cssp.model.InitiateMultipartUploadResult;
import com.toycloud.business.dto.results.CommonResult;
import com.toycloud.common.core.utils.DateUtils;
import com.toycloud.system.utils.Openstorage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;


@RestController
@RequestMapping("/upload")
@Slf4j
public class FileUploadController {


    private static final String ACCOUNT = "hipanda";

    private static final String ACCESS_KEY_ID = "ae851fee56c241af925b36bc67267e85";
    private static final String ACCESS_SECRET = "c111b64da78146fea14121ced2316465";
    private static final String COM_URL = "http://hipanda.hfdn.openstorage.cn/";
    private static final String RETURN_URL = "http://hipanda.hf.openstorage.cn/";
    private static final String PRIVRES_KEY = "UG9egbforqN05dwQjMPpXsLb9JohYqys";

    //新的域名 toycloud
    private static final String NEW_COMMON_URL = "https://hipanda-cdn-ws.toycloud.com/";
    private static final String NEW_RETURN_URL = "https://hipanda-cdn-ws.toycloud.com/";
    @Autowired
    private Openstorage openstorage;

    // 上传分片文件
    @PostMapping("/chunk")
    public String uploadChunk(@RequestParam("file") MultipartFile file,
                              @RequestParam("fileName") String fileName) {

////        String fileName = fileId + "/chunk-" + chunkIndex;  // 生成每个分片的文件名
//
//        try (InputStream stream = file.getInputStream()) {
//            String url = openstorage.uploadFileNew(stream, "talkres", "demand", fileName);  // 上传分片
////            if (chunkIndex + 1 == totalChunks) {
////                // 可在所有分片上传完毕后执行合并操作，具体实现视云存储API而定
////                System.out.println("所有分片上传完成");
////            }
//            return url;
//        } catch (IOException e) {
//            e.printStackTrace();
//            return "";
//        }
        String path =null;
        String url = null;

            if (file.getContentType().startsWith("image/")) {
                path = "FeedbackImage";
            }else if(file.getContentType().startsWith("video/")){
                path="FeedbackVideo";
            }else if(file.getContentType().equals("application/vnd.ms-excel") ||
                    file.getContentType().equals("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")){
                path="FeedbackExcel";
            }else if(file.getContentType().equals("application/vnd.ms-powerpoint") ||
                    file.getContentType().equals("application/vnd.openxmlformats-officedocument.presentationml.presentation")
            ){
                path="FeedbackPPT";
            }

        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();

        // 提取文件扩展名
        String fileExtension = "";
        if (originalFilename != null && originalFilename.contains(".")) {
            fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        }

        // 为文件名添加时间戳
        String timeStamp = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
        String newFileName = timeStamp + "_" + originalFilename; // 新的文件名

        try (InputStream stream = file.getInputStream()) {
                url = openstorage.uploadFileNew(stream, "talkres", path, newFileName);  // 上传分片
            } catch (IOException e) {
                e.printStackTrace();
                return "上传云存储报错";
            }
        return url;
    }

    public String multipartUpload(InputStream fileStream, String containerName, String folder, String fileName, long partSize) {
        // 设置目标对象名称
        String objectName = (StringUtils.hasLength(folder) ? folder + "/" : "") + fileName;
        String url = COM_URL + containerName;
        CSSPClient client = new CSSPClient();
        boolean success = false;

        try {
            client.Client(ACCESS_KEY_ID, ACCESS_SECRET, url);
        } catch (CSSPException e) {
            log.error("初始化CSSPClient失败：" + e.getMessage());
            return "";
        }

        // 1. 初始化分段上传，获取UploadID
        String uploadID;
        try {
            uploadID = initiateMultipartUpload(client, objectName);
        } catch (CSSPException | IOException e) {
            log.error("初始化分段上传失败：" + e.getMessage());
            return "";
        }

        // 2. 分割文件并逐个上传分片
        try {
            byte[] buffer = new byte[(int) partSize];
            int partNumber = 1;
            int bytesRead;
            while ((bytesRead = fileStream.read(buffer)) != -1) {
                InputStream partStream = new ByteArrayInputStream(buffer, 0, bytesRead);
                client.uploadPart(objectName, partStream, bytesRead, null, uploadID, partNumber++);
                partStream.close();
            }
        } catch (CSSPException | IOException e) {
            log.error("上传分片失败：" + e.getMessage());
            return "";
        }

        // 3. 完成分片上传
        try {
            completeMultipartUpload(client, objectName, uploadID);
            success = true;
        } catch (CSSPException | IOException e) {
            log.error("分片上传合并失败：" + e.getMessage());
            return "";
        }

        // 返回完整文件URL
        System.out.println(NEW_RETURN_URL + containerName + "/" + objectName);
        return success ? NEW_RETURN_URL + containerName + "/" + objectName : "";
    }

    // 初始化分段上传，返回UploadID
    private String initiateMultipartUpload(CSSPClient client, String objectName) throws CSSPException, IOException {
        InitiateMultipartUploadResult result = client.initiateMultipartUploadRequest(objectName);
        return result.getUploadID();
    }

    // 完成分段上传
    private void completeMultipartUpload(CSSPClient client, String objectName, String uploadID) throws CSSPException, IOException {
        client.completeMultipartUpload(objectName, uploadID);
    }


}
